package com.javastar.common.exception;

import com.javastar.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 自定义全局异常处理器
 *
 * @author zxx
 * @date 2023/7/23
 */
@RestControllerAdvice
@Slf4j
public class NovelExceptionHandler {

    /**
     * 处理授权异常
     * @param ex
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result handleAccessDeniedException(AccessDeniedException ex) {
        log.error("handleNovelException:     " + ex.getMessage(), ex);
        return new Result().error(ErrorCode.ACCESS_DENIED_ERROR);
    }

    /**
     * 处理自定义异常
     * @param ex
     * @return
     */
    @ExceptionHandler(NovelException.class)
    public Result handleNovelException(NovelException ex) {
        log.error("handleNovelException:     " + ex.getMsg(), ex);
        return new Result().error(ex.getCode(), ex.getMsg());
    }

    /**
     * 处理全局异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception ex) {
        log.error("handleException:    " + ex.getMessage(), ex);
        return new Result().error(ErrorCode.INTERNAL_SERVER_ERROR);
    }

}
